<template>
  <div class="hompage" id="map">
    <OlMap @mapClick="mapClick" ref="dialog" @updatemap="updatemap"></OlMap>
  </div>
</template>

<script setup>
import OlMap from "@/components/map/olMap.vue";
import { onMounted, ref } from "vue";
import svgimg from "@/assets/mapimg/point/mission-point.png";
import KspMap from "@/components/map/utils/kspmap";
import $ from "jquery";
import MapUtils from "@/components/map/utils/map-utils";
import { Circle as CircleStyle } from 'ol/style'
import { Circle, LinearRing } from "ol/geom";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Style from "ol/style/Style";
import Stroke from "ol/style/Stroke";
import Fill from "ol/style/Fill";
import { GeoJSON } from "ol/format";
import { boundingExtent } from "ol/extent";
import Text from "ol/style/Text";
import { Feature } from "ol";
import { fromExtent } from "ol/geom/Polygon";
import { transformExtent } from "ol/proj";
import Mask from 'ol-ext/filter/Mask'
import Crop from 'ol-ext/filter/Crop'
import 'ol-ext/dist/ol-ext.min.css';
import TileLayer from "ol/layer/Tile";
import { OSM } from "ol/source";
let KspMapclass;
let dialog = ref();
let updateMapdata = null;
let geojsonLayer = null
let featuresList = []
// 线图层
onMounted(() => { });
function updatemap(map) {
  if (map) {
    updateMapdata = map;
    KspMapclass = new KspMap(updateMapdata);
    wmsHoverLayer()
    wfsPolygon()
    KspMapclass.addMapEvent('singleclick', move)
    updateMapdata.on('pointermove', mapPointermove)

  }
}
function move(params) {
  console.log(params);
}

function mapPointermove(event) {
  geojsonLayer && geojsonLayer.getSource().clear()
  let feature = updateMapdata.forEachFeatureAtPixel(
    event['pixel'],
    (feature) => {
      return feature
    }
  )
  if (feature) {
    geojsonLayer.getSource().addFeature(feature)
  }

  console.log(feature);
}

// 鼠标移动的图层
function wmsHoverLayer() {
  // 鼠标移动上去的图层
  geojsonLayer = new VectorLayer({
    source: new VectorSource(),
    zIndex: 9999,
    style: new Style({
      stroke: new Stroke({
        color: 'red',
        // lineDash: [4],
        width: 1,
      }),
      fill: new Fill({
        color: 'rgba(255,0,0, 0.5)',
      }),
    }),
  })
  updateMapdata.addLayer(geojsonLayer)
}

let masklayer = null
// 查询行政区划线
function wfsPolygon() {
  let url = '/api/360922.json'
  let vectorSource = new VectorSource({
    format: new GeoJSON(),
  });
  let wmsLayer = new VectorLayer({
    source: vectorSource,
    zIndex: 99,
    style: (feature) => {
      let text = feature.get("name");
      return new Style({
        stroke: new Stroke({
          color: 'rgba(40,120,255, 0.8)',
          // lineDash: [4],
          width: 1,
        }),
        fill: new Fill({
          color: 'rgba(40,120,255, 0.8)',
        }),
        text: new Text({
          text: text,
          font: '14px Calibri,sans-serif',
          fill: new Fill({
            color: '#fff',
          }),
          stroke: new Stroke({
            color: 'rgba(40,120,255, 0.5)',
            width: 3,
          }),
        }),
      })
    }
  })
  updateMapdata.addLayer(wmsLayer);


  let innerLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      stroke: new Stroke({
        width: 10,
        color: 'rgba(255,255,255, 0.4)'
      }),
      fill: new Fill({
        color: 'rgba(40,120,255, 0)'
      })
    }),
    zIndex: 2
  });
  updateMapdata.addLayer(innerLayer);

  //outer
  let outerLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      stroke: new Stroke({
        width: 5,
        color: 'rgba(255,255,255, 0.4)'
      }),
      fill: new Fill({
        color: 'rgba(40,120,255, 0)'
      })
    }),
    zIndex: 2
  });
  updateMapdata.addLayer(outerLayer);




  masklayer = new VectorLayer({
    source: new VectorSource(),
    style: new Style({
      fill: new Fill({
        color: 'rgba(40,120,255, 0.8)',
      }),
      stroke: new Stroke({
        color: 'transparent',
      }),
    }),
    zIndex: 11,
  })
  updateMapdata.addLayer(masklayer)

  $.ajax({
    type: "GET",
    url: url,
    success: (result) => {
      let coordinates = [];
      for (let f of result["features"]) {
        let feature = new GeoJSON().readFeatures(f);
        if (feature[0].getGeometry()) {

          let geom = feature[0]
            .getGeometry()
            .transform("EPSG:4326", "EPSG:3857");
          feature[0].setGeometry(geom);
          vectorSource.addFeatures(feature);
          featuresList.push(feature);
          const extents = geom.getExtent();
          coordinates.push(
            [extents[0], extents[1]],
            [extents[2], extents[3]]
          );

        }
      }
      extent = boundingExtent(coordinates);
      updateMapdata.getView().fit(extent, {
        size: updateMapdata.getSize(),
        padding: [150, 150, 150, 150],
        duration: 800,
      }); //居中到geometry视野中
      console.log(featuresList);

      // addMask(result)
    },
    error: function (jq) {
      console.log("失败", jq);
    },
  });

  let extent = null;

  let f = new GeoJSON().readFeature(require('@/assets/360922.json').features[0])
  var mask = new Mask({
    feature: f,
    wrapX: true,
    inner: false,
    fill: new Fill({ color: [0, 0, 0, 0.7] })
  });
  var crop = new Crop({
    feature: f,
    wrapX: true,
    inner: false
  });
  // 若不加天地图就直接将osmlayer 使用addFilter 就行
  // osmBaseLayer.addFilter(crop);
  // osmBaseLayer.addFilter(mask);

  // let tdtImgLayer = createTDTImg();
  // tdtImgLayer.addFilter(crop);
  // tdtImgLayer.addFilter(mask);
  // const osmBaseLayer = new TileLayer({
  //       source:new OSM()
  //     })
  masklayer.addFilter(crop);
  masklayer.addFilter(mask);
  // updateMapdata.addLayer(osmBaseLayer)


}


// 添加蒙版
function addMask(featureGeometry) {
  masklayer.getSource().clear()
  let vectorSource = new VectorLayer({
    features: [
      new Feature({
        geometry: erase(featureGeometry),
      }),
    ],
  })



  // const fts = new GeoJSON().readFeatures(data);
  // const ft = fts[0];
  // console.log(ft);
  // const converGeom = erase(ft.getGeometry());
  // const convertFt = new Feature({
  //   geometry: converGeom,
  // });
  // vectorSource.getSource().addFeature(convertFt);
  masklayer.setSource(vectorSource)

}

function erase(geom) {
  const extent = [-180, -90, 180, 90];
  const polygonRing = fromExtent(extent);
  const coords = geom.getCoordinates();
  coords.forEach(coord => {
    const linearRing = new LinearRing(coord[0]);
    polygonRing.appendLinearRing(linearRing);
  });
  return polygonRing;
}


/**
 * 清除图层
 */
function claer() {
  KspMapclass.removeVectorLayer("areas_v3");
  KspMapclass.deleteAllDrawFeature()
}



</script>

<style scoped>
.hompage {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0px;
  left: 0px;

}

#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
}

.point {
  position: absolute;
  top: 10px;
  left: 10px;
}

.btn-box {
  position: absolute;
  top: 20px;
  left: 100px;
  z-index: 999;
}

.btn-box button {
  margin-right: 10px;
}

.clear {
  z-index: 999;
}
</style>
